<template>
	<section class="music_detail">

		<div class="detailTop">
			<van-nav-bar :title="data.SongName" border fixed left-text="返回" left-arrow @click-left="$router.back()">
				<template #right>
					<van-icon name="share-o" @click="isShare" />
				</template>
			</van-nav-bar>
			<van-share-sheet v-model:show="showShare" title="立即分享给好友" :options="options" />
		</div>

		<!-- 专辑封面 -->
		<div class="detailCenter">

			<img src="@/assets/musicDetails/needle-ab.png" :class="{ 'img_needle': true, 'img_needle_do': data.isPlay }"
				alt="">
			<img src="@/assets/musicDetails/cd.png" :class="{ 'img_cd': true, 'active': data.isPlay }">
			<img :src="bgImg" class="bgImg" alt="">
			<img :src="bgImg" :class="{ 'img_default': true, 'active': data.isPlay }">

			<!-- 播放动效 -->
			<div class="container-wrap">
				<div :class="{ 'container': true }">
					<div :class="{ 'more': true, 'active': data.isPlay }"></div>
					<div :class="{ 'more': true, 'active': data.isPlay }"></div>
					<div :class="{ 'more': true, 'active': data.isPlay }"></div>
					<div :class="{ 'more': true, 'active': data.isPlay }"></div>
				</div>
			</div>
			<!-- <lyric v-show="true"></lyric> -->
		</div>


		<div class="detailFooter">
			<div class="footerTop">
				<van-icon name="like-o" />
				<van-icon name="pause-circle-o" />
				<van-icon name="like-o" />
				<van-icon name="pause-circle-o" />
				<van-icon name="more-o" />
			</div>
			<div class="slidBar">
				<div class="timeBar">
					<div class="time">
						<span>{{ data2.realMusicTime }}</span>
						<div class="bar" ref="bar" @click="handClickBar">
							<div class="slid" ref="slid" @click="handClickBar">
							</div>

						</div>
						<span>{{ data.totalMusicTime }}</span>
					</div>
				</div>
			</div>
			<div class="footer">
				<van-icon name="exchange" @click="switchMusic" />
				<van-icon name="arrow-left" @click="handlePrevMusic" />
				<!-- :class="isPlay ? 'active' : ''" @click="play" -->
				<van-icon class="stop" v-show="data.isPlay" name="pause-circle-o" @click="play" />
				<van-icon class="stop" v-show="!data.isPlay" name="play-circle-o" @click="play" />
				<van-icon name="arrow" @click="handleNextMusic" />
				<van-icon name="apps-o" @click="showPlayMenu" />
				<div class="songMenu" v-show="data.isShowPlayMenu">
					<div class="closePlayMenu">
						<strong>当前播放
							<span>
								( {{ songsData.length }} )
							</span>
						</strong>
						<span @click="closePlayMenu">X</span>
					</div>
					<div class="menu">
						<van-sidebar v-model="active" @change="onChange" v-for="item in songsData" :key="item.id">
							<van-sidebar-item :title="item.name" @click="changSong(item.id)" />
						</van-sidebar>
					</div>
				</div>
			</div>
			<audio ref="music" :src="audio" :autoplay="data.isPlay" @play="isPlayMusic" @ended="switchMusic"
				@canplay="canplaysong" @timeupdate="handlMusicTime"></audio>
		</div>

	</section>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue';
import { RequestSteetAllSongs } from "@/api/homeFind"
import { MusicDetail, RequestNewSongs } from "@/api/MusicDetail";
import { useRoute } from "vue-router"
// import lyric from "@/views/MusicDetail/lyric1.vue"


import { getLyric } from '@/api/MusicDetail';
const lyric1 = ref()


const music = ref(null);
const slid = ref(null);
const bar = ref(null)
const route = useRoute()
const audio = ref()
const audioSrcs = ref([])
const bgImg = ref(null)
const active = ref(0);
const SongName = ref([])
const data2 = ref({
	realMusicTime: "00:00",
})
const songsData = ref({}) //歌单信息
const data = reactive({
	id: "",
	playlist: "",//歌单
	isPlay: true,
	totalMusicTime: "00:00",
	randomNum: 0,
	// songsData: {},//歌单信息
	SongName: '',
	isShowPlayMenu: false
});

onMounted(async () => {
	data.id = Number(route.query.id)
	data.playlist = Number(route.query.steetId)
	rukou(data.id, data.playlist)
	// console.log(SongName);
	// console.log(songsData.value);
	getLyricFun(1993340900)

});


async function rukou(id, playList) {
	// 歌单
	if (playList) {
		songsData.value = (await RequestSteetAllSongs(playList)).data.songs
		// songsData.value = temp.data.songs
		let res = await MusicDetail(id)
		playListMusic()
		findCurrenntSong(id)
		audio.value = res.data.data[0].url
	} else {
		// 新歌速递
		songsData.value = (await RequestNewSongs(7)).data.data
		let res = await MusicDetail(id)
		audio.value = res.data.data[0].url
		findCurrenntSong(id)
	}
}

// 歌词获取
function getLyricFun(id) {
	console.log(1);

	if (lyric1.value) {
		// getLyric本身返回的就是Promise
		return Promise.resolve(lyric1.value);
	}
	// 封装Promise，只用于获取歌词
	return new Promise((resolve, reject) => {
		getLyric(id).then((res) => {
			if (res.data.lrc.version === 8) {
				lyric1.value = res.data.lrc.lyric;
				resolve(lyric1.value);
				console.log(lyric1.value);

			} else {
				// 获取不到歌词
				// eslint-disable-next-line prefer-promise-reject-errors
				reject('no lyric');
			}
		});
	});
}

function currentSong(newSong, oldSong) {
	if (newSong.id === oldSong.id) {
		return;
	}
	nextTick(() => {
		audio.value.play().catch((error) => {
			// this.togglePlaying();
			// eslint-disable-next-line no-alert
			alert('播放出错,暂无该歌曲资源');
		});
		getLyricFun(newSong.id);
	});
}

const onChange = (item) => Toast()
async function changSong(id) {
	data.isPlay = false
	findCurrenntSong(id)
	let res = await MusicDetail(id)
	audio.value = res.data.data[0].url
	music.value.load()
	// 文件下载完毕，如果不用等到全部下载完毕，可以用canplay事件
	music.value.addEventListener("canplaythrough", () => {
		music.value.play();
		data.isPlay = true;
	})
}


function showPlayMenu() {
	data.isShowPlayMenu = true
	playListMusic()
}
function closePlayMenu() {
	data.isShowPlayMenu = false
}

// 获取所有歌单歌曲
function playListMusic() {
	let playList = songsData.value
	// 把歌单所有歌曲的id传入audioSrcs
	// console.log(playList);

	playList.forEach(item => {
		audioSrcs.value.push(item.id)
		SongName.value.push(item.name)
	})
}

// 分享组件
function isShare() {
	showShare.value = true
}
const showShare = ref(false);
const options = [
	[
		{ name: '微信', icon: 'wechat' },
		{ name: '朋友圈', icon: 'wechat-moments' },
		{ name: '微博', icon: 'weibo' },
		{ name: 'QQ', icon: 'qq' },
	],
	[
		{ name: '复制链接', icon: 'link' },
		{ name: '分享海报', icon: 'poster' },
		{ name: '二维码', icon: 'qrcode' },
		{ name: '小程序码', icon: 'weapp-qrcode' },
	],
];

//通过当前歌曲id渲染图片等
function findCurrenntSong(id) {

	let songMune = songsData.value
	// console.log(songMune);

	songMune.forEach(item => {
		// 添加歌单所有歌曲id
		audioSrcs.value.push(item.id)
		if (item.id == id) {
			// 封面地址，判断是歌单还是歌曲速递
			if (item.al) {
				bgImg.value = item.al.picUrl
				data.SongName = item.name
			} else if (item.album) {
				bgImg.value = item.album.blurPicUrl
				// 歌曲名字	
				data.SongName = item.name
			}

		}
	});
}
//根据id在AudioSrcS中找到歌曲链接
async function AccordingIdFindMusic(musicId) {
	let NewMusicId = audioSrcs.value[musicId];
	let res = await MusicDetail(NewMusicId)
	audio.value = res.data.data[0].url
	findCurrenntSong(NewMusicId)
}
// // // 处理进度条
function handMusicBar() {
	// setInterval(() => {
	let duration = music.value.duration//总时间
	let currentTime = music.value.currentTime
	let x = ((currentTime / duration) * 100).toFixed(2) + "%";
	slid.value.style.width = x;
	// }, 0)

}
// 处理点击进度条事件
function handClickBar(e) {
	const barTotalWidth = bar.value.offsetWidth; // bar 总宽度
	const rect = e.target.getBoundingClientRect(); // 元素右边距离页面边距的距离 返回上下左右
	let length = e.pageX - rect.left;
	music.value.currentTime = length / barTotalWidth * music.value.duration; // 计算播放时间 位置百分比*总时间
	nextTick(() => {
		music.value.play();
		data.isPlay = true;
	})
}

//播放暂停
function isPlayMusic() {

}
function play() {
	if (music.value.paused) {
		music.value.play();
		data.isPlay = true;
		data.isShow = true;
	} else {
		music.value.pause();
		data.isPlay = false;
		data.isShow = false;
		// console.log(RequestLogin);
	}

}
//随机切换歌曲
function switchMusic() {
	data.isPlay = false;
	data.randomNum = Math.floor(Math.random() * audioSrcs.value.length);
	AccordingIdFindMusic(data.randomNum)
	// 预加载下一首
	data.randomNum++
	music.value.load()
	// 文件下载完毕，如果不用等到全部下载完毕，可以用canplay事件
	music.value.addEventListener("canplaythrough", () => {
		music.value.play();
		data.isPlay = true;
	})
}

//下一曲
//边界问题
function handleNextMusic() {
	data.isPlay = false;
	music.value.pause();
	// 边界判断	
	let currentMusic = data.randomNum++
	if (currentMusic >= audioSrcs.value.length) {
		data.randomNum = 0
		AccordingIdFindMusic(data.randomNum)
		music.value.load()//歌曲预加载
		music.value.addEventListener("canplaythrough", () => {
			music.value.play();
			data.isPlay = true;
		})
	} else {
		AccordingIdFindMusic(data.randomNum)
		music.value.load()
		music.value.addEventListener("canplaythrough", () => {
			music.value.play();
			data.isPlay = true;
		})
	}
}
// 上一曲
function handlePrevMusic() {
	data.isPlay = false;
	music.value.pause();
	// 边界判断
	let currentMusic = data.randomNum--
	if (currentMusic <= 0) {
		data.randomNum = audioSrcs.value.length
		AccordingIdFindMusic(data.randomNum)
		music.value.load()
		music.value.addEventListener("canplaythrough", () => {
			music.value.play();
			data.isPlay = true;
		})
	} else {
		AccordingIdFindMusic(currentMusic)
		music.value.load()
		music.value.addEventListener("canplaythrough", () => {
			music.value.play();
			data.isPlay = true;
		})
	}
}


function canplaysong() {
	// 总时间
	let total = parseInt(music.value.duration)
	data.totalMusicTime = total
	let minute = total % 60
	let seconds = (total - minute) / 60
	data.totalMusicTime = seconds + ':' + minute


}

//当前时间
function handlMusicTime() {
	let displayTime: number = Math.floor(music.value.currentTime);//获取实时时间
	// 分钟
	let minute2: number = parseInt(displayTime / 60);
	if (minute2 < 10) {
		minute2 = "0" + minute2;
	}
	//秒
	let second2 = Math.round(displayTime % 60);
	if (second2 < 10) {
		second2 = "0" + second2;
	}
	handMusicBar()
	data2.value.realMusicTime = minute2 + ":" + second2;
}


</script>

<style lang="scss" scoped>
section[class="music_detail"] {
	height: 100%;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
	width: 100%;
	animation-play-state: paused; // 暂定动画

	.detailTop {
		height: 2rem;
		width: 100%;
		display: flex;
		justify-content: space-between;

		animation-play-state: paused; // 暂定动画

		.van-nav-bar__content {
			animation-play-state: paused; // 暂定动画

			.van-nav-bar__left {
				animation-play-state: paused; // 暂定动画
			}

			.van-nav-bar__title {
				animation-play-state: paused; // 暂定动画
			}

			.singer {
				display: flex;
				flex-direction: column;
				justify-content: center;
				align-items: center;

				&>strong {
					font-size: 0.5rem;
				}

				&>span {
					font-size: 0.4rem;
				}
			}
		}

	}

	.detailCenter {
		width: 100%;
		height: 9rem;
		display: flex;
		justify-content: center;
		flex-direction: column;
		align-items: center;
		position: relative;

		//针
		.img_needle {
			width: 2.5rem;
			height: 3rem;
			position: absolute;
			left: 46%;
			transform-origin: -650% -100%;
			// transform-origin: -650% 100%;
			transform: rotate(-10deg);
			transition: all 1s;
			z-index: 1;
		}

		.img_needle_do {
			// transform-origin: -600% -140%;
			transform-origin: -650% 100%;
		}

		.img_cd {
			width: 5rem;
			height: 5rem;
			position: absolute;
			bottom: 2rem;
			animation: musicRotate 10s linear infinite;
			animation-play-state: paused; // 暂定动画
			z-index: -1;
		}

		.bgImg {
			position: absolute;
			filter: blur(20px);
			z-index: -10;
			height: 10rem;
		}



		.img_default {
			width: 3.2rem;
			height: 3.2rem;
			border-radius: 50%;
			position: absolute;
			bottom: 2.9rem;
			animation: musicRotate 10s linear infinite;
			animation-play-state: paused; // 暂定动画
		}

		.active {
			animation-play-state: running; // 运行动画
		}

		.container-wrap {
			width: 50%;
			height: 6rem;
			display: block;
			margin: 50px auto 0 auto;
			overflow: hidden;

			.container {
				// position: relative;
				width: 6.25rem;
				height: 6.25rem;
				margin: 0 auto;
				border-radius: 50%;
				margin-top: 200px;

				.more {
					position: absolute;
					z-index: -3;
					opacity: 1;
					left: 0;
					right: 0;
					top: 0;
					bottom: 0;
					margin: auto;
					width: 4rem;
					height: 4rem;
					border-radius: 50%;
					border: 1px solid rgb(226, 191, 191);
					animation: routerView 4s linear 0s infinite;
					animation-play-state: paused; // 暂定动画

					&::after {
						content: "";
						position: absolute;
						top: -4px;
						left: 50%;
						width: 6px;
						height: 6px;
						overflow: hidden;
						border-radius: 5px;
						background-color: rgba(182, 243, 122, 0.77);
					}

					&:nth-child(2) {
						animation-delay: 1s;
					}

					&:nth-child(3) {
						animation-delay: 2s;
					}

					&:nth-child(4) {
						animation-delay: 3s;
					}

					&.active {
						animation-play-state: running; // 运行动画
					}
				}
			}
		}


	}

	.detailFooter {
		height: 4rem;
		display: flex;
		flex-direction: column;
		justify-content: space-between;

		.footerTop {
			width: 100%;
			display: flex;
			justify-content: space-evenly;
		}

		.slidBar {
			width: 100%;
			box-sizing: border-box;
			padding: .625rem;

			.time {
				width: 100%;
				display: flex;
				justify-content: space-between;
				align-items: center;

				.bar {
					width: 80%;
					height: 0.1rem;
					background-color: #f8eaea;
					border-radius: 8px;
					position: relative;
					border-radius: 8px;
					overflow: hidden;
					cursor: pointer;

					.slid {
						position: absolute;
						left: 0;
						top: 0;
						background-color: #e24d80;
						height: 100%;
						width: 0;
						transition: width 0.3s;
					}
				}

				span {
					font-size: .375rem;
					margin: .3125rem;
				}
			}

		}

		.footer {
			width: 100%;
			display: flex;
			justify-content: space-evenly;

			.stop {
				cursor: pointer;
			}

			.songMenu {
				position: absolute;
				border-radius: .3125rem .3125rem 0 0;
				background-color: rgba(104, 84, 109, 0.411);
				width: 90%;
				bottom: 0;
				height: 8rem;
				z-index: 10;
				box-sizing: border-box;
				display: flex;
				flex-direction: column;

				.closePlayMenu {
					width: 100%;
					box-sizing: border-box;
					color: #f8eaea;
					height: 1.2rem;
					display: flex;
					justify-content: space-between;
					padding: .1875rem;

					strong {

						// position: fixed;
						// bottom: 6.8rem;
						// left: 1.4rem;
						span {
							font-size: 0.5rem;
						}
					}

					.closePlayMenu {
						// position: fixed;
						// bottom: 6.8rem;
						// right: 1.4rem;
					}
				}

				.menu {
					width: 100%;
					height: 8.5rem;
					overflow: auto;
					border-radius: .3125rem .3125rem 0 0;

					.van-sidebar {
						width: 100%;
						background-color: rgba(104, 84, 109, 0.411);
						border-bottom: 1px solide #f8eaea;

						.van-sidebar-item {
							width: 100%;
							background-color: rgba(104, 84, 109, 0.411);
							color: #f8eaea;
							padding: .3rem;
							border-bottom: 1px solide #f8eaea;
						}
					}
				}





			}

		}


	}

	// 黑胶旋转动画 
	@keyframes musicRotate {
		from {
			transform: rotate(0);
		}

		to {
			transform: rotate(360deg);
		}
	}

	@keyframes routerView {
		0% {
			opacity: 1;
			transform: rotate(0deg) scale(1);
		}

		25% {
			opacity: 0.75;
			transform: rotate(72deg) scale(1.25);
		}

		50% {
			opacity: 0.5;
			transform: rotate(144deg) scale(1.5);
		}

		75% {
			opacity: 0.25;
			transform: rotate(216deg) scale(1.75);
		}

		100% {
			opacity: 0;
			transform: rotate(360deg) scale(2);
		}
	}
}
</style>
